package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableSuperMemberRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TagSuperMemberRecord {
    public long uid;
    public int super_member_member_type;
    public int super_member_auto_renew;
    public int update_time;

    public static Logger LOG = LoggerFactory.getLogger(TagSuperMemberRecord.class);

    public TagSuperMemberRecord() {}

    public TagSuperMemberRecord(
            long uid, int super_member_member_type, int super_member_auto_renew, int update_time) {
        this.uid = uid;
        this.super_member_member_type = super_member_member_type;
        this.super_member_auto_renew = super_member_auto_renew;
        this.update_time = update_time;
    }

    public static TagSuperMemberRecord init(long uid) {
        return new TagSuperMemberRecord(uid, -1, -1, 0);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableSuperMemberRecord.QUERYSQL);
        DataStream<Tuple2<Boolean, TableSuperMemberRecord>> inputStream =
                tableEnv.toRetractStream(tableRes, TableSuperMemberRecord.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableSuperMemberRecord>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableSuperMemberRecord> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagSuperMemRecord-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableSuperMemberRecord>, Long>() {
                                    @Override
                                    public Long getKey(
                                            Tuple2<Boolean, TableSuperMemberRecord> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(new SuperMemberRecordFlatMapFunciton());

        return out;
    }

    private static class SuperMemberRecordFlatMapFunciton
            extends RichFlatMapFunction<Tuple2<Boolean, TableSuperMemberRecord>, String> {
        ValueState<TagSuperMemberRecord> superMemRecordVState;
        MapState<Long, Integer> superMemAutoRenewMState;

        @Override
        public void open(Configuration parameters) throws Exception {
            superMemRecordVState =
                    getRuntimeContext()
                            .getState(
                                    new ValueStateDescriptor<TagSuperMemberRecord>(
                                            "SuperMemRecordVState", TagSuperMemberRecord.class));
            superMemAutoRenewMState =
                    getRuntimeContext()
                            .getMapState(
                                    new MapStateDescriptor<Long, Integer>(
                                            "superMemAutoRenewMState", Long.class, Integer.class));
        }

        @Override
        public void flatMap(Tuple2<Boolean, TableSuperMemberRecord> value, Collector<String> out)
                throws Exception {

            long id = value.f1.getId();
            long uid = value.f1.getUid();
            int status = (int) value.f1.getStatus();
            int member_type = (int) value.f1.getMember_type();
            int auto_renew = (int) value.f1.getAuto_renew();
            int update_time = (int) (value.f1.getUpdate_time().getTime() / 1000);
            int delete_time = (int) (value.f1.getDelete_time().getTime() / 1000);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("uid", uid);

            int super_member_auto_renew = 0;

            TagSuperMemberRecord tmpState = superMemRecordVState.value();
            TagSuperMemberRecord curState =
                    (tmpState == null ? TagSuperMemberRecord.init(uid) : tmpState);

            /**
             * 超级会员是否自动续费 1：是，0：否 ；
             * 只要有一条auto_renew = 1的数据，该用户是会员自动续费
             * 会员退费情况：当数据为 auto_renew = 1 and delete_time is null 时，数据删除时，先更新 auto_renew = 0，然后更新 delete_time is not null
             * 会员到期情况：当数据为 auto_renew = 1 and delete_time is null 时，数据删除时，不更新 auto_renew = 0，只更新 delete_time值
             */
            if (delete_time == 0 && auto_renew == 1 && status != 2) {
                if (!superMemAutoRenewMState.contains(id)) {
                    superMemAutoRenewMState.put(id, -1);
                }
            } else {
                if (superMemAutoRenewMState.contains(id)) {
                    superMemAutoRenewMState.remove(id);
                }
            }
            if (!superMemAutoRenewMState.isEmpty()) {
                super_member_auto_renew = 1;
            }
            if (super_member_auto_renew != curState.getSuper_member_auto_renew()) {
                jsonObject.put("super_member_auto_renew", super_member_auto_renew);
                curState.super_member_auto_renew = super_member_auto_renew;
                superMemRecordVState.update(curState);
            }

            /** 比对新老会员变更情况 及 会员类型 */
            if (status == 1 && delete_time == 0 && update_time > curState.getUpdate_time()) {
                // 超级会员会员类型 0：年卡，1：季卡
                if (member_type != curState.getSuper_member_member_type()) {
                    jsonObject.put("super_member_member_type", member_type);
                    curState.super_member_member_type = member_type;
                }
                // 有数据进入就更新update_time
                curState.update_time = update_time;
                superMemRecordVState.update(curState);
            }

            if (jsonObject.size() > 1) {
                out.collect(jsonObject.toString());
            }
        }
    }

    public long getUid() {
        return uid;
    }

    public int getSuper_member_member_type() {
        return super_member_member_type;
    }

    public int getSuper_member_auto_renew() {
        return super_member_auto_renew;
    }

    public int getUpdate_time() {
        return update_time;
    }

    @Override
    public String toString() {
        return "TagSuperMemberRecord{"
                + "uid="
                + uid
                + ", super_member_member_type="
                + super_member_member_type
                + ", super_member_auto_renew="
                + super_member_auto_renew
                + ", update_time="
                + update_time
                + '}';
    }
}
